package io.renren.modules.report.controller;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import io.renren.modules.report.entity.ConnectUserEntity;
import io.renren.modules.report.service.ConnectUserService;
import io.renren.modules.report.vo.ConnectionUserVO;
import io.renren.modules.report.vo.SelectedVO;
import io.renren.modules.report.vo.UserVO;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.report.entity.ConnectionEntity;
import io.renren.modules.report.service.ConnectionService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author august
 * @email 379249906@qq.com
 * @date 2020-07-06 16:53:43
 */
@RestController
@RequestMapping("report/connection")
public class ConnectionController {
    @Autowired
    private ConnectionService connectionService;

    @Autowired
    private SysUserService sysUserService;



    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = connectionService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 获取所有的用户
     */
    @RequestMapping("/users")
    public R users(@RequestParam Map<String, Object> params){
        String connectId = (String)params.get("connectId");
        List<UserVO> collect;
        if(connectId==null){
             collect = sysUserService.list().stream().map(item -> {
                UserVO userVO = new UserVO();
                userVO.setValue(item.getUserId());
                userVO.setLabel(item.getUsername());
                return userVO;
            }).collect(Collectors.toList());
        }else{
            collect = connectionService.getUsersbyConnectionID(Long.parseLong(connectId));
        }

        return R.ok().put("userList", collect);
    }

    /**
     * 获取所有的链接
     */
    @RequestMapping("/connections")
    public R connections(){
        List<SelectedVO> collect = connectionService.list().stream().map(item -> {
            SelectedVO selectedVO = new SelectedVO();
            selectedVO.setValue(item.getId());
            selectedVO.setLabel(item.getName());
            return selectedVO;
        }).collect(Collectors.toList());

//        List<UserVO> collect;
//        if(connectId==null){
//            collect = sysUserService.list().stream().map(item -> {
//                UserVO userVO = new UserVO();
//                userVO.setValue(item.getUserId());
//                userVO.setLabel(item.getUsername());
//                return userVO;
//            }).collect(Collectors.toList());
//        }else{
//            collect = connectionService.getUsersbyConnectionID(Long.parseLong(connectId));
//        }

        return R.ok().put("connectionList", collect);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		ConnectionEntity connection = connectionService.getById(id);

        return R.ok().put("connection", connection);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ConnectionUserVO connectionUserVO){


        connectionService.saveCascade(connectionUserVO);


        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ConnectionUserVO connectionUserVO){
        connectionService.updateCascade(connectionUserVO);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		//connectionService.removeByIds(Arrays.asList(ids));
        connectionService.deleteCascade(ids);
        return R.ok();
    }

    @GetMapping("/connect/{id}")
    public R connection(@PathVariable("id") Long id){
        ConnectionEntity connection = connectionService.getById(id);
        String driverName = connection.getDriverName();
        String databaseName = connection.getDatabaseName();

        String connectUrl="";
        String driverUrl="";
        if("mysql".equalsIgnoreCase(driverName)){
            driverUrl="com.mysql.cj.jdbc.Driver";
            //jdbc:mysql://localhost:3306/renren_fast?useUnicode=true&characterEncoding=UTF-8
            connectUrl="jdbc:mysql://"+connection.getIp()+":"+connection.getPort()+"/"
                    +databaseName+"?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        }

        String connectUsername = connection.getConnectUsername();
        String connectPassword = connection.getConnectPassword();

        try {
            Class.forName(driverUrl);
            Connection conn = DriverManager.getConnection(connectUrl, connectUsername, connectPassword);

        } catch (Exception e) {
            return R.error("连接出错!");
        }
        return R.ok("连接成功!");
    }

}
